package com.yunxin.download.server.infra.support.file.export.service;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.yunxin.download.server.infra.constant.enums.FileTypeEnum;
import com.yunxin.download.server.infra.support.file.FileHeader;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;


/**
 * EasyExcel导出实现
 * @author zero°
 * @since 2023-06-15
 */
@Slf4j
public class XlsxFileExportServiceImpl implements FileExportService {

    private WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();

    private ExcelWriter excelWriter;

    private OutputStream outputStream;


    @Override
    public void init(String sheetName, Class<? extends FileHeader> excelHeaderClass, OutputStream outputStream) {
        writeSheet = new WriteSheet();
        writeSheet.setSheetName(sheetName);
        excelWriter = new ExcelWriterBuilder()
                .excelType(ExcelTypeEnum.XLSX)
                .file(outputStream)
                .head(excelHeaderClass)
                .build();
        this.outputStream = outputStream;
    }

    @Override
    public void init(String fileName, InputStream inputStream, OutputStream outputStream) {
        writeSheet = new WriteSheet();
        excelWriter = new ExcelWriterBuilder()
                .excelType(ExcelTypeEnum.XLSX)
                .file(outputStream)
                .withTemplate(inputStream)
                .build();
        this.outputStream = outputStream;
    }

    @Override
    public void append(List<Object> data) {
        if (!data.isEmpty()) {
            excelWriter.write(data, writeSheet);
        }
    }

    @Override
    public void appendByMap(List<Map<String, Object>> data) {
        if (!data.isEmpty()) {
            excelWriter.fill(data, writeSheet);
        }
    }

    @Override
    public OutputStream finish() {
        if (excelWriter != null) {
            excelWriter.finish();
        }
        return this.outputStream;
    }

    @Override
    public String getFileTypeSuffix() {
        return FileTypeEnum.XLSX.getType();
    }
}
